package top.archiesean.common.redis.biz;

import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

/**
 * @author ArchieSean
 * @description 分布式锁工具类
 * @date 2024-01-01 00:18
 */
public class LockService {
    private static final int TIME_OUT = 60;
    @Resource
    private RedissonClient redissonClient;


    /**
     * 获取分布式锁对象
     *
     * @param key 加锁关键字
     * @return RLock
     */
    public RLock getLock(String key) {
        return redissonClient.getLock(key);
    }


    /**
     * 是否已获取锁
     *
     * @param lock 参数
     * @return boolean
     */
    public boolean isLocked(RLock lock) {
        try {
            int waitTime = 0;
            return lock.tryLock(waitTime, TIME_OUT, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 释放锁
     *
     * @param lock 参数
     */
    public void unlock(RLock lock) {
        if (!isLockedByCurrentThead(lock)) {
            throw new RuntimeException("锁不是当前线程的");
        }
        lock.unlock();
    }

    /**
     * 判断是否是当前线程加的锁
     *
     * @param lock 参数
     * @return boole
     */
    private boolean isLockedByCurrentThead(RLock lock) {
        try {
            return lock.isHeldByCurrentThread();
        } catch (Exception e) {
            return false;
        }
    }
}
